package nix.hibernate.many;

import nix.domain.Role;
import nix.domain.User;
import nix.utils.HibernateUtils;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

public class DemoMany2Many {

	@Test
	public void fun1() {
		Session session = HibernateUtils.getSession();
		Transaction tx = session.beginTransaction();
		// 创建瞬时对象
		User u1 = new User();
		u1.setUser_name("张三");		
		User u2 = new User();
		u2.setUser_name("李四");
		Role r1 = new Role();
		r1.setRole_name("保洁");
		Role r2 = new Role();
		r2.setRole_name("保安");
		// 装配关系（多对多 根据业务方向，必须有一方放弃维护关系）
		u1.getRoles().add(r1);
		// r1.getUsers().add(u1);
		u1.getRoles().add(r2);
		// r2.getUsers().add(u1);
		u2.getRoles().add(r1);
		// r1.getUsers().add(u2);
		u2.getRoles().add(r2);
		// r2.getUsers().add(u2);
		// 持久化
		session.save(u1);
		session.save(u2);
		session.save(r1);
		session.save(r2);
		
		tx.commit();
		session.close();
	}
	
	@Test
	public void fun2() {
		Session session = HibernateUtils.getSession();
		Transaction tx = session.beginTransaction();
		// 获得持久化对象
		User u1 = (User) session.get(User.class, 1L);
		// 创建瞬时状态对象
		Role r1 = new Role();
		r1.setRole_name("公关");
		// 装配关系
		u1.getRoles().add(r1);
		// 持久化
		session.save(r1);
		
		tx.commit();
		session.close();
	}
	
	@Test
	public void fun3() {
		Session session = HibernateUtils.getSession();
		Transaction tx = session.beginTransaction();
		// 获得持久化对象
		User u1 = (User) session.get(User.class, 1L);
		Role r1 = (Role) session.get(Role.class, 1L);
		Role r2 = (Role) session.get(Role.class, 2L);
		// 移除关系
		u1.getRoles().remove(r1);
		u1.getRoles().remove(r2);

		tx.commit();
		session.close();
	}
}
